using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using Newtonsoft.Json.Linq;
using Spine.Unity;
using UnityEngine;
using UnityEngine.UI;

public class Goods : MonoBehaviour
{
    public GameObject tray;
    public GameObject icon;
    public GameObject shadow;
    public GameObject iconShadow;
    public GameObject trayShadow;
    public int goodsId;
    public bool isBack;
    public Image iconImage;
    private bool isSelected = false;
    private Sequence selectAnimation;
    public Container container;
    public CanvasGroup canvasGroup;
    private Rigidbody2D rb;
    public bool IsOnFloor = false;
    public bool IsOnCart = false;
    private SkeletonGraphic skeletonGraphic;
    public Transform skeTransform;

    private void Awake()
    {
        canvasGroup = GetComponent<CanvasGroup>();
        skeletonGraphic = skeTransform.GetComponent<SkeletonGraphic>();
        // 订阅动画完成事件
        skeletonGraphic.AnimationState.Complete += OnAnimationComplete;
    }

    private void OnDestroy()
    {

    }

    private void OnAnimationComplete(Spine.TrackEntry trackEntry)
    {
        // 判断当前播放的动画是否是我们关注的动画
        if (trackEntry.Animation.Name == "animation")
        {
            //销毁
            skeletonGraphic.AnimationState.Complete -= OnAnimationComplete;
        }
    }

    public void Init(JObject data)
    {
        // if (!container.isLock)
        // {
        GoodsManager.Instance.RegisterGoods(this);
        // }
        gameObject.name = "Goods";
        goodsId = (int)data["goodsId"];
        iconShadow.SetActive(false);
        // trayShadow.SetActive(false);

        Sprite[] sprites = ResManager.Instance.GetGoodsIcons();
        // 获取sprite
        Sprite currentSprite = sprites[goodsId];

        // 设置sprite
        iconShadow.GetComponent<Image>().sprite = currentSprite;
        shadow.GetComponent<Image>().sprite = currentSprite;
        icon.GetComponent<Image>().sprite = currentSprite;

        // 设置原始图像大小
        iconShadow.GetComponent<Image>().SetNativeSize();
        shadow.GetComponent<Image>().SetNativeSize();
        icon.GetComponent<Image>().SetNativeSize();

        isBack = (bool)data["isBack"];

        iconShadow.SetActive(isBack);
        // trayShadow.SetActive(isBack);

        BackFrontEffect();
    }

    public void OnClickGoods()
    {
        if (isBack) return;
        // 点击事件
        Debug.Log("点击了商品" + goodsId);
        int _level = (int)UserManager.Instance.GetUserInfo()["CurrentLv"];
        int on = PlayerPrefs.GetInt("OrderNotification", 0);
        if (Data.mode == 0 && _level > 1 && on == 0)
        {
            // PanelManager.Instance.OpenPanel<OrderNotificationPanel>();
            // PlayerPrefs.SetInt("OrderNotification", 1);
        }
        if (Data.mode == 1)
        {
            ToggleSelect();
            return;
        }

        gameObject.transform.SetParent(Data.rigidContainer);
        GoodsManager.Instance.UnregisterGoods(this);

        if (gameObject.GetComponent<Rigidbody2D>() == null)
        {
            gameObject.AddComponent<Rigidbody2D>();
        }
        rb = gameObject.GetComponent<Rigidbody2D>();

        // 创建一个序列
        Sequence sequence = DOTween.Sequence();
        // 按顺序添加两个动画
        sequence.Append(gameObject.transform.DOScale(1f, 0.2f))
                // .AppendInterval(0.1f)
                // .Append(gameObject.transform.DOMoveY(gameObject.transform.position.y - 50, 0.3f))
                // .AppendInterval(0.1f)
                .OnComplete(() =>
                    {
                        EnablePhysics();

                        //等待0.2秒
                        StartCoroutine(WaitSeconds());
                    });
    }

    public IEnumerator WaitSeconds()
    {
        // 等待指定的时间（秒转换为毫秒）
        yield return new WaitForSeconds(0.4f);

        bool isFrontEmpty = container.IsFrontEmpty();
        if (isFrontEmpty)
        {
            container.BackToFront();
        }
    }

    // 启用物体的物理模拟
    public void EnablePhysics()
    {
        if (rb != null)
        {
            rb.simulated = true;
        }
    }

    // 禁用物体的物理模拟
    public void DisablePhysics()
    {
        if (rb != null)
        {
            rb.simulated = false;
        }
    }


    public void ToggleSelect()
    {
        isSelected = !isSelected;
        if (isSelected)
        {
            AudioManager.Instance.PlaySoundEffect("sounds_click");
            PlaySelectAnimation();
        }
        else
        {
            AudioManager.Instance.PlaySoundEffect("sounds_unselect");
            ResetSelectAnimation();
        }
    }

    private void PlaySelectAnimation()
    {
        GoodsManager.Instance.SelectGoods(this);

        // 停止并清除之前的动画（如果有）
        if (selectAnimation != null)
        {
            selectAnimation.Kill();
        }

        // 创建新的动画序列
        selectAnimation = DOTween.Sequence();

        // 放大效果
        selectAnimation.Append(transform.DOScale(1f, 0.15f).SetEase(Ease.OutQuad));

        // 颜色变化效果（假设我们使用一个Image组件来显示图标）
        if (iconImage != null)
        {
            selectAnimation.Join(iconImage.DOColor(new Color(1f, 0.8f, 0.8f), 0.3f));
        }

        // 轻微上下浮动效果
        selectAnimation.Append(transform.DOLocalMoveY(transform.localPosition.y + 15f, 0.5f)
            .SetEase(Ease.InOutSine)
            .SetLoops(-1, LoopType.Yoyo));
    }

    private void ResetSelectAnimation()
    {
        GoodsManager.Instance.ResetSelectedGoods();

        // 停止并清除动画
        if (selectAnimation != null)
        {
            selectAnimation.Kill();
        }

        // 重置缩放
        transform.DOScale(0.9f, 0.2f);

        // 重置颜色
        if (iconImage != null)
        {
            iconImage.DOColor(Color.white, 0.2f);
        }

        // 重置位置
        transform.DOLocalMoveY(0f, 0.2f);
    }

    public void Deselect()
    {
        if (isSelected)
        {
            isSelected = false;
            ResetSelectAnimation();
        }
    }

    public void SetFront()
    {
        isBack = false;

        iconShadow.SetActive(isBack);
        // trayShadow.SetActive(isBack);
    }

    public void PlayAnimation()
    {
        // 播放动画
        skeletonGraphic.AnimationState.SetAnimation(0, "animation", false);
    }
    public IEnumerator SetClearCoroutine()
    {
        bool isComplete = false;
        PlayAnimation();
        float tesla = Random.Range(3, 6);
        UserManager.Instance.AddTesla(tesla);

        canvasGroup.DOFade(0, 0.3f)
        .OnComplete(() =>
            {
                gameObject.transform.SetParent(null);
                Destroy(gameObject);
                if (Data.mode == 1)
                {
                    GoodsManager.Instance.UnregisterGoods(this);
                }
                isComplete = true;
            });
        // 等待动画完成和 OnKill 回调执行
        while (!isComplete)
        {
            yield return null;
        }
    }

    public void OnRemoveMask()
    {
        iconShadow.SetActive(false);
        // trayShadow.SetActive(false);
    }

    public void OnFadeOut()
    {
        canvasGroup.DOFade(0, 0.1f)
            .OnComplete(() =>
            {
                gameObject.transform.SetParent(null);
                Destroy(gameObject);
            });
    }

    public void BackFrontEffect()
    {
        Sequence sequence = DOTween.Sequence();
        transform.localScale = Vector3.zero;
        sequence.Join(transform.DOScale(1f, 0.2f))
                .Append(transform.DOScale(0.9f, 0.2f));
    }

    public void ChangeGoods(int gid)
    {
        Sprite[] sprites = ResManager.Instance.GetGoodsIcons();
        // 获取sprite
        Sprite currentSprite = sprites[gid];

        // 设置sprite
        iconShadow.GetComponent<Image>().sprite = currentSprite;
        shadow.GetComponent<Image>().sprite = currentSprite;
        icon.GetComponent<Image>().sprite = currentSprite;

        // 设置原始图像大小
        iconShadow.GetComponent<Image>().SetNativeSize();
        shadow.GetComponent<Image>().SetNativeSize();
        icon.GetComponent<Image>().SetNativeSize();

        goodsId = gid;
        shadow.SetActive(true);
    }

    public void SetOnFloor(bool tag)
    {
        IsOnFloor = tag;
    }
}
